package com.jiubanqingchen.wish.framework.directive;

import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.TemplateException;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;

/**
 * #like like查询指令
 * #like(n)默认全like
 * #like(n,patten) L(left like) R(right like) N(not like) NL(not left like) NR(not right like)
 * @author light_dust
 * @since 2020/07/16
 */
public class ParaLikeDirective extends Directive {

    private Expr valueExpr;

    private Expr patternExpr;

    @Override
    public void exec(Env env, Scope scope, Writer writer) {
        Object value = valueExpr.eval(scope);
        if (value == null) {
            return;
        }
        if (patternExpr == null) {
            outputWithoutPattern(writer, value);
        } else {
            outputWithPattern(scope, writer, value);
        }
    }

    @Override
    public void setExprList(ExprList exprList) {
        int paraNum = exprList.length();
        if (paraNum == 0) {
            throw new ParseException("The parameter of #paraLike directive can not be blank", location);
        }
        if (paraNum > 2) {
            throw new ParseException("Wrong like parameter of #paraLike directive, two parameters allowed at most", location);
        }
        valueExpr = exprList.getExpr(0);
        patternExpr = (paraNum == 1 ? null : exprList.getExpr(1));
    }

    private void outputWithoutPattern(Writer writer, Object value) {
        String ret = "like '%" + value + "%'";
        write(writer, ret);
    }

    private void outputWithPattern(Scope scope, Writer writer, Object value) {
        Object pattern = patternExpr.eval(scope);
        if (!(pattern instanceof String)) {
            throw new TemplateException("The second parameter pattern of #paraLike directive must be String", location);
        }
        String patternStr = pattern.toString();
        String ret ;
        switch (patternStr) {
            case "L":
                ret = "like '%" + value+"'";
                break;
            case "R":
                ret = "like '" + value + "%'";
                break;
            case "N":
                ret = "not like '%" + value + "%'";
                break;
            case "NL":
                ret = "not like '%" + value+"'";
                break;
            case "NR":
                ret = "not like '" + value + "%'";
                break;
            default:
                ret="";
        }
        write(writer, ret);
    }
}

